package com.zyg.cod.util;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.util.*;

public class WriteFileUtil {

    /**
     * 将string内容追加写到到目录里的文件上，不覆盖原来的数据
     */
    public static boolean writeString2File2(String path, String name, String str) throws Exception {
        boolean writeSuccessFlag = true;
        FileWriter fwriter = null;
        try {
            // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
            fwriter = new FileWriter(path+name, true);
            fwriter.write(str);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return writeSuccessFlag;
    }
    /**
     * 将string内容写到指定文件指定文件夹里
     */
    public static boolean writeString2File(String path, String name, String str) throws Exception {
        boolean writeSuccessFlag = true;
        //如果指定路径不存在，创建
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = path + name;
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        PrintWriter out = null;
        try {
            fos=new FileOutputStream(fileName);
            osw = new OutputStreamWriter(fos, "utf-8");
            out = new PrintWriter(osw);
            out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(fos);
        }
        return writeSuccessFlag;
    }

    /**
     * 得到指定路径下的所有文件，按文件修改时间(由小到大)返回文件集合
     */
    public static List<File> getSortFilesByPath(String path) {
        List<File> fileList = new LinkedList<File>();
        //不递归文件夹得到所有文件
        fileList = getFilesByPath(path);
        //排序文件
        if (fileList != null && fileList.size() > 0) {
            Collections.sort(fileList, new Comparator<File>() {
                public int compare(File file, File newFile) {
                    if (file.lastModified() > newFile.lastModified()) {
                        return 1;//返回正值，按以上相反排序，即小的放前面
                    } else if (file.lastModified() == newFile.lastModified()) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
        }
        return fileList;
    }

    /**
     * 得到指定路径下的所有文件夹的所有文件
     */
    public static List<File> getAllFilesByPath(String path) {
        List<File> fileList = new ArrayList<File>();
        File dir = new File(path);
        File[] files = dir.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    getAllFilesByPath(files[i].getAbsolutePath());
                } else if (files[i].getName().toLowerCase().endsWith(".xml")) {
                    fileList.add(files[i]);
                }
            }
        }
        return fileList;
    }

    /**
     * 得到指定路径下的所有文件，不递归文件夹
     */
    public static List<File> getFilesByPath(String path) {
        List<File> fileList = new ArrayList<File>();
        File dir = new File(path);
        File[] files = dir.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    //不递归文件夹
                } else if (files[i].getName().toLowerCase().endsWith(".xml")) {//只获取xml文件
                    fileList.add(files[i]);
                }
            }
        }
        return fileList;
    }

    /**
     * 移动指定文件到指定目录，并删除原报文
     */
    public static boolean moveAndDeleteFile(File file, String targetPath) throws Exception {
        //如果指定目录不存在，创建
        File f = new File(targetPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        boolean flag = false;
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader read = null;
        OutputStreamWriter osw = null;
        PrintWriter out = null;
        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis, "utf-8");
            read = new BufferedReader(isr);
            osw = new OutputStreamWriter(new FileOutputStream(targetPath + "\\" + file.getName()),
                    "utf-8");
            out = new PrintWriter(osw);
            String readContent = null;
            while ((readContent = read.readLine()) != null) {
                out.println(readContent);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(file.getName() + "原报文删除失败！");
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(read);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(fis);
            //如果写没抛异常，删除源文件
            if (flag) {
                file.delete();
            }
        }
        return flag;
    }

    /**
     * 复制文件
     * @param file
     * @param targetPath
     * @return
     * @throws Exception
     */
    public static synchronized boolean copyFile(File file, String targetPath) throws Exception {
        File file1 = new File(targetPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        boolean flag = true;
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader read = null;
        OutputStreamWriter osw = null;
        PrintWriter out = null;
        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis, "utf-8");
            read = new BufferedReader(isr);
            osw = new OutputStreamWriter(new FileOutputStream(targetPath + "\\" + file
                    .getName()), "utf-8");
            out = new PrintWriter(osw);
            String readContent = null;
            while ((readContent = read.readLine()) != null) {
                out.println(readContent);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(read);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(fis);
        }
        return flag;
    }

    /**
     * 将file转为string
     */
    public static String file2String(File file) {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader buffer = null;
        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis, "utf-8");
            buffer = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String temp;
            while ((temp = buffer.readLine()) != null) {
                sb.append(temp);
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        } finally {
            IOUtils.closeQuietly(buffer);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(fis);
        }
    }

}
